package com.cal.utms.dao.maintenance;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.cal.utms.entity.ScreenConfirmation;
import com.cal.utms.util.HibernateUtil;

public class ScreenConfirmationDao {
	
	public Object add(ScreenConfirmation screenConfirmation) {
		Object obj;
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		System.out.println("Saving ScreenConfirm: "+ screenConfirmation.getScreen());
		try {
			tx = session.beginTransaction();
			obj = session.save(screenConfirmation);
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
			obj = new Object();
			System.out.println("Exception in save ScreenConfirm: " + screenConfirmation.getScreen() + " : " + ex.getMessage());
			ex.printStackTrace();
		} finally {
			session.close();
		}
		return obj;
	}
	
	public void addList(String screen, List<ScreenConfirmation> scList) {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		System.out.println("Saving ScreenConfirmList");
		List<ScreenConfirmation> oldScList = getByScreen(screen);
		try {
			tx = session.beginTransaction();
			for(ScreenConfirmation scOld: oldScList){
				session.delete(scOld);
			}			
			for(ScreenConfirmation sc: scList){
				session.save(sc);
			}
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
			System.out.println("Exception in save ScreenConfirm: " + ex.getMessage());
			ex.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	public void delete(ScreenConfirmation screenConfirmation) {
		System.out.println("Deleting ScreenConfirm "+screenConfirmation.getScreen());
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.delete(screenConfirmation);
			tx.commit();
			System.out.println("ScreenConfirm deleted");
		} catch (Exception ex) {
			tx.rollback();
			System.out.println("Exception in Deleting the ScreenConfirm: " + screenConfirmation.getScreen() + " : " + ex.getMessage());
			ex.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	
	@SuppressWarnings("unchecked")
	public List<ScreenConfirmation> getByScreen(String screen) {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<ScreenConfirmation> scList = null;
		try {
			tx = session.beginTransaction();
			Query query = session.createQuery("select c from ScreenConfirmation c where c.screen = :screen");
			query.setParameter("screen", screen);
			scList = query.list();
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			System.out.println("Exception getByScreen Fund " + e.getMessage());
			e.printStackTrace();
		} finally {
			session.close();
		}
		return scList;
	}

}
